import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('@/views/web/Blog.vue')
    },
    {
      path: '/detail/:id',
      component: () => import('@/views/web/Detail.vue')
    },
    {
      path: '/login',
      component: () => import('@/views/login/Login.vue')
    },
    {
      path: '/admin',
      redirect: '/admin/home', // 首页
      component: () => import('@/views/layout/Layout.vue'),
      children: [
        {
          path: '/admin/article', // 文章列表
          component: () => import('@/views/admin/Article.vue')
        },
        {
          path: '/admin/category', // 分类
          component: () => import('@/views/admin/Category.vue')
        },
        {
          path: '/admin/home', // 首页
          component: () => import('@/views/admin/Home.vue')
        },
        {
          path: '/admin/post', // 写文章
          component: () => import('@/views/admin/Post.vue')
        },
        {
          path: '/admin/tag', // 标签
          component: () => import('@/views/admin/Tag.vue')
        },
        {
          path: '/admin/user',
          component: () => import('@/views/admin/UserInfo.vue')
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/components/404.vue')
    }
  ]
})

// 路由守卫

router.beforeEach((to) => {
  const userStroe = useUserStore()
  if (to.path.startsWith('/admin') && !userStroe.getToken()) {
    ElMessage.success('请先登录')
    router.push('/login')
  }
})
export default router
